/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx.activity.ConversationActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.easeui.widget.MyTitleBar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.activity.ForwardDetailsActivity;
import com.srwl.mytx.im.conversation.Conversation;
import com.srwl.mytx.greendao.MessageDao;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.NotifyMessageAdapter;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.Advertisement;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Forward;
import com.srwl.mytx.domain.Orders;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.Transfer;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.service.ForwardService;
import com.srwl.mytx.widget.ConfirmDialog;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Application and notification
 */
@Deprecated
public class NotifyActivity extends BaseActivity implements NotifyMessageAdapter.InteractionListener {
    public static void startActivity(Context context, int conversationType) {
        context.startActivity(new Intent(context, NotifyActivity.class).putExtra("conversationType", conversationType));
    }

    private static final String TAG = "NotifyActivity";
    public static final int REQUEST_CODE_TO_ORDER_DETAIL = 1;
    public static final int REQUEST_CODE_TO_TRANSFER_DETAIL = 3;
    public static final int REQUEST_CODE_TO_SET_ADVERTISEMENT = 4;
    public static final int REQUEST_CODE_TO_VERIFY_TOPIC = 5;
    private RecyclerView rv_notify;
    private MessageDao messageDao;
    List<Message> notifyList = new ArrayList<>();
    ;
    RecyclerView.Adapter adapter;
    MyTitleBar titleBar;
    ProgressBar progressBar;
    private int conversationType;
    private Conversation conversation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        conversationType = getIntent().getIntExtra("conversationType", -1);
        rv_notify = findViewById(R.id.rv_notify);
        if (conversationType == Constant.CONVERSATION_TYPE_CONTACT) {
            conversation = IMSClientBootstrap.getInstance().getConversationService().getC2cConversation(Constant.CONVERSATION_TYPE_CONTACT + "");
            notifyList.addAll(conversation.firstLoadMessage(20));
            rv_notify.setLayoutManager(new LinearLayoutManager(this));
            adapter = new NotifyMessageAdapter(this, notifyList, this);
        }
        setContentView(R.layout.activity_notice_message);
        titleBar = findViewById(R.id.title_bar);
        progressBar = findViewById(R.id.progress_bar);
        messageDao = DBManager.getInstance().getDaoSession().getMessageDao();
        rv_notify.setAdapter(adapter);
        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 弹出自定义对话

                ConfirmDialog dialog = new ConfirmDialog(NotifyActivity.this, "提示", "确定删除所有通知消息吗？", true);
                dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                    @Override
                    public void confirm() {
                        notifyList.clear();
                        adapter.notifyDataSetChanged();
                        conversation.deleteAllMessage();

                    }
                });
                dialog.show();
            }
        });

        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void showForwardDetail(String forwardId) {
        toForwardDetail(forwardId);
    }

    void toForwardDetail(String forwardId) {
        if (!Helper.getInstance().isNetworkConnected()){
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(ForwardService.class)
                .getForwardInfo_v1(forwardId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() && result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }

                        JSONObject jsonObject = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse:获取转赠详情完成 " + jsonObject.toString());
                        Forward fullForward = jsonObject.toJavaObject(Forward.class);
                        startActivity(new Intent(NotifyActivity.this, ForwardDetailsActivity.class).putExtra(Constant.EXTRA_INFO_FORWARD, fullForward));

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);

                        showToast(getString(R.string.system_busy));
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_CODE_TO_ORDER_DETAIL) {
            Orders updateOrder = data.getParcelableExtra(Constant.EXTRA_INFO_ORDER);
            for (int i = 0; i < notifyList.size(); i++) {
                Message notify = notifyList.get(i);
                if (notify.getSubType() == Constant.PUSH_MESSAGE_OFFER_TO_TOPIC_SUCCESS) {//成功支付定单的返回结果
                    Orders order = JSONObject.parseObject(notify.getContent(), Orders.class);
                    if (order == null) {
                        continue;
                    }
                    if (TextUtils.equals(updateOrder.getId(), order.getId())) {
                        if (updateOrder.getCreated() != null && order.getUpdated() != null && updateOrder.getUpdated().before(order.getUpdated())) {//说明回传的订单信息已经过时，不能覆盖最新信息，直接 break,
                            break;
                        }
                        order.setStatus(updateOrder.getStatus());
                        notify.setContent(JSONObject.toJSONString(order));
                        adapter.notifyItemChanged(i);
                        messageDao.update(notify);
                        break;
                    }
                }
            }
        } else if (requestCode == REQUEST_CODE_TO_TRANSFER_DETAIL) {
            //修改数据库中对应消息的信息
            Transfer updateTransfer = data.getParcelableExtra(Constant.EXTRA_INFO_TRANSFER);
            for (int i = 0; i < notifyList.size(); i++) {
                Message notify = notifyList.get(i);
                //判断消息类型是否为提现订单类型
                if (notify.getSubType() == Constant.PUSH_MESSAGE_APPLY_WITHDRAW) {
                    Transfer transfer = JSONObject.parseObject(notify.getContent(), Transfer.class);
                    if (transfer == null) {
                        continue;
                    }
                    if (TextUtils.equals(updateTransfer.getId(), transfer.getId())) {
                        transfer.setStatus(updateTransfer.getStatus());
                        transfer.setPayDate(updateTransfer.getPayDate());
                        notify.setContent(JSONObject.toJSONString(transfer));
                        adapter.notifyItemChanged(i);
                        messageDao.update(notify);
                        break;
                    }
                }
            }
        } else if (requestCode == REQUEST_CODE_TO_SET_ADVERTISEMENT) {

            Advertisement updateAdvertisement = data.getParcelableExtra("advertisement");
            for (int i = 0; i < notifyList.size(); i++) {
                Message notify = notifyList.get(i);
                if (notify.getSubType() == Constant.PUSH_MESSAGE_ADVERTISEMENT_OFFER_SUCCESS) {
                    Advertisement advertisement = JSONObject.parseObject(notify.getContent(), Advertisement.class);
                    if (advertisement == null) {
                        continue;
                    }
                    if (TextUtils.equals(updateAdvertisement.getId(), advertisement.getId())) {
                        notify.setContent(JSONObject.toJSONString(updateAdvertisement));
                        adapter.notifyItemChanged(i);
                        messageDao.update(notify);
                        break;
                    }
                }
            }

        } else if (requestCode == REQUEST_CODE_TO_VERIFY_TOPIC) {

            Topic updateTopic = data.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
            for (int i = 0; i < notifyList.size(); i++) {
                Message notify = notifyList.get(i);
                if (notify.getSubType() == Constant.PUSH_MESSAGE_TOPIC_VERIFY) {
                    Topic topic = JSONObject.parseObject(notify.getContent(), Topic.class);
                    if (topic == null) {
                        continue;
                    }
                    if (TextUtils.equals(updateTopic.getId(), topic.getId())) {
                        notify.setContent(JSONObject.toJSONString(updateTopic));
                        adapter.notifyItemChanged(i);
                        messageDao.update(notify);
                        break;
                    }
                }
            }

        }

    }
}
